package com.threeox.ormlibrary.util;

import com.threeox.utillibrary.util.RegexUtils;

import java.util.regex.Matcher;

/**
 *
 * @ClassName: SqlHelper
 *
 * @Description: TODO()
 *
 * @author 赵屈犇
 *
 * @date 创建时间: 2017/8/14 18:31
 *
 * @version 1.0
 *
 */
public class SqlHelper {

    /**
     * 得到查询总数的sql语句
     *
     * @param countSql
     * @return
     */
    public static String getSqlCount(String countSql) {
        String regex = "(?i)SELECT((?:(?!\\}_)[\\s\\S])*)(?i)FROM";
        Matcher matche = RegexUtils.getMatche(regex, countSql);
        if (matche == null)
            return null;
        while (matche.find()) {
            countSql = countSql.replace(matche.group(1), " COUNT(*) ");
        }
        return countSql;
    }

    /**
     * 得到查询的sql语句
     *
     * @param sqlFrom
     * @return
     */
    public static String getSqlFrom(String sqlFrom) {
        String regex = "(?i)SELECT((?:(?!\\}_)[\\s\\S])*)(?i)FROM";
        Matcher matche = RegexUtils.getMatche(regex, sqlFrom);
        if (matche == null)
            return sqlFrom;
        if (matche.find()) {
            return sqlFrom;
        } else {
            return "SELECT * FROM " + sqlFrom;
        }
    }

}
